package com.wx.push.subscription.push.utils;


import com.wx.push.subscription.push.bo.JsonRootBean;
import com.wx.push.subscription.push.config.SubscriptionConfig;
import com.wx.push.subscription.push.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 01424605
 * @create 2022-08-22 14:35
 */
@Slf4j
public class PusherUtil {

//     todo 配置类测试号的appId和secret
    private static String appId="wx0b733e286e2013b0";
    private static String secret = "2c67d7f75d00c2dea3b8d089bc81a275";

    //模版id todo 配置类
//    @Value("${subscription.morningTemplateId}")
    private static String morningTemplateId = "DIqFdOPz4THeJGOkl02quf6P9zKcfD9arrvOI2McS9M";

    private static String caiHongPiUrl = "http://api.tianapi.com/caihongpi/index";

    private static String healthTipUrl="http://api.tianapi.com/healthtip/index";
    private static String healthTipKey = "3d6f98e93c56503d2e40d3ca8eb3972c";



    @Autowired
    SubscriptionConfig subscriptionConfig;

    public void getSubscriptionConfig(){
        String appId = SubscriptionConfig.appId;
//        String secret = subscriptionConfig.getSecret();
    }

    public static void pushMessage(UserInfoVo user){
        //1，配置
        //2,推送消息
        String openId = user.getOpenId();
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId(morningTemplateId)
                //.url("https://30paotui.com/")//点击模版消息要访问的网址
                .build();
        //3,如果是正式版发送模版消息，这里需要配置你的信息
        String userName = user.getUserName();
        String cityCode = user.getCityCode();
        String birthdayTime = user.getBirthdayTime();
        String msg = user.getMsg();
        String uniqueMsg = user.getUniqueMsg();
        String memorialDayMsgTime = user.getMemorialDayMsg();
        String sendMsg = user.getSendMsgVo().getSendMsg();

        //称呼
        templateMessage.addData(new WxMpTemplateData("userName", userName));
        //每日一言
        templateMessage.addData(new WxMpTemplateData("msg", msg));
        String unique = "你没有特权，不能查看此消息";
        if(!StringUtils.isEmpty(uniqueMsg)){
            unique = "独有的情话：❤️" + uniqueMsg;
        }
        templateMessage.addData(new WxMpTemplateData("uniqueMsg",unique));


        //填写变量信息，比如天气之类的
        JsonRootBean weather = BaiduWeatherUtil.getWeather(cityCode);
        if (weather == null){
            log.error("{},调用百度天气失败:{}",new Date(),userName);
            return;
        }
        String city = weather.getResult().getLocation().getCity();
        //日期
        Date todayDate = weather.getResult().getForecasts().get(0).getDate();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatTime = simpleDateFormat.format(todayDate);

        //今日天气
        String todayCondition = weather.getResult().getForecasts().get(0).getText_day();
        int todayHigh = weather.getResult().getForecasts().get(0).getHigh();
        int todayLow = weather.getResult().getForecasts().get(0).getLow();
        //明日天气
        String tomorrowCondition = weather.getResult().getForecasts().get(1).getText_day();
        int tomorrowHigh = weather.getResult().getForecasts().get(1).getHigh();
        int tomorrowLow = weather.getResult().getForecasts().get(1).getLow();

        templateMessage.addData(new WxMpTemplateData("todayDate",formatTime,"#3399CC"));
        templateMessage.addData(new WxMpTemplateData("city",city,"#3399CC"));
        templateMessage.addData(new WxMpTemplateData("todayCondition",todayCondition,"#FF4500"));
        templateMessage.addData(new WxMpTemplateData("todayHigh",todayHigh + "","#000000" ));
        templateMessage.addData(new WxMpTemplateData("todayLow",todayLow + "","#000000"));
        templateMessage.addData(new WxMpTemplateData("tomorrowCondition",tomorrowCondition,"#FF4500"));
        templateMessage.addData(new WxMpTemplateData("tomorrowHigh",tomorrowHigh+ "","#000000" ));
        templateMessage.addData(new WxMpTemplateData("tomorrowLow",tomorrowLow + "","#000000"));
        //彩虹屁
//        String caiHongPi = MsgApiUtil.getAMessage(caiHongPiUrl, caiHongPiKey, "");
//        templateMessage.addData(new WxMpTemplateData("caiHongPi", caiHongPi,"#FF69B4"));
        //励志古言
//        String motivate = MsgApiUtil.getAMessage(motivatePiUrl, motivatePiKey, "");
//        templateMessage.addData(new WxMpTemplateData("motivate",motivate+"","#C71585"));
        //健康小意见
        String healthTip = MsgApiUtil.getAMessage(healthTipUrl, healthTipKey, "");
        templateMessage.addData(new WxMpTemplateData("healthTip",healthTip+"","#99CC66"));
        //纪念日
        String memorialDayMsg = "你是普通用户，没有纪念日提醒功能哦~~";
        if(!StringUtils.isEmpty(memorialDayMsgTime)){
            String memorialDay = ImportantTimeUtil.hasTime(memorialDayMsgTime);
            memorialDayMsg = "我们已经恋爱了"+memorialDay + "啦~~";
        }
        templateMessage.addData(new WxMpTemplateData("memorialDay", memorialDayMsg,"#FF99CC"));
        //生日
        String birthdayDay = "我不晓得你的生日哦~";
        if(!StringUtils.isEmpty(birthdayTime)){
            birthdayDay = ImportantTimeUtil.getBirthDay(birthdayTime);
        }
        templateMessage.addData(new WxMpTemplateData("birthdayDay",birthdayDay,"#993399"));
        String everySendMsg = "没有人给你留言哦~~";
        if(!StringUtils.isEmpty(sendMsg)){
            everySendMsg = sendMsg;
        }
        templateMessage.addData(new WxMpTemplateData("sendMsg",everySendMsg,"#FFA500"));

        pushToWx(templateMessage);
    }

    public static void pushToWx(WxMpTemplateMessage templateMessage){
        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(appId);
        wxStorage.setSecret(secret);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        try {
            log.info("公众号推送的消息:{}", templateMessage.toJson());
//            System.out.println(templateMessage.toJson());
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            log.info("推送失败:{}",e.getMessage());
            e.printStackTrace();
        }
    }

}
